//
//  NSObject+Js.m
//  JSGategoryLib
//
//  Created by allumos on 03/27/2018.
//  Copyright (c) 2018 allumos. All rights reserved.
//

#import "NSObject+Js.h"

@implementation NSObject (Js)
/**
 *  解决输出中文乱码问题
 *
 *  @return 字符串
 */
- (NSString *)wj_description
{
    NSString *desc = [self description];
    desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
    return desc;
}
/**
 *  string 转 字典
 *
 *  @return 字典
 */
+ (NSDictionary *)wj_dictionaryWithJsonString:(NSString *)outString
{
    if (outString == nil) {
        return nil;
    }
    NSData *jsonData = [outString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

/**
 *  字典 转 json格式字符串
 *
 *  NSJSONWritingPrettyPrinted  是有换位符的。
 *  如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有 换位符的
 *
 *  @return 返回json
 */
+ (NSString*)wj_dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
/**
 *  json 转 数组或者字典
 *
 *  @return 点点或者数组
 */
+ (id)wj_toArrayOrNSDictionary:(NSData *)jsonData
{
    
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:nil];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
    
}

/**
 *  字典拼接字符串Http传值使用
 *
 *  @return 拼接好的字符串
 */
+ (NSString *)wj_connectString:(NSMutableDictionary *)params
{
    // 初始化参数变量
    NSString *str = @",";
    
    // 快速遍历参数数组
    for(id key in params) {
        //        NSLog(@"key :%@  value :%@", key, [params objectForKey:key]);
        str = [str stringByAppendingString:key];
        str = [str stringByAppendingString:@"="];
        str = [str stringByAppendingString:[params objectForKey:key]];
        str = [str stringByAppendingString:@","];
    }
    // 去掉首尾的&
    str = [str substringWithRange:NSMakeRange(1,str.length - 2)];
    return str;
    
}



@end
